// pages/guess/index.js
var app = getApp();
const recorderManager = wx.getRecorderManager();//录音管理
// const innerAudioContext = wx.createInnerAudioContext();//播放音频
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: 0,
    speak: true,
    isspeaks: true,
    listen: 'xxx',
    open:0,
    //分页
    page: 1
  },
  shouye: function (e) {
    console.log(e);
    wx.navigateTo({
      url: '/pages/voice_box/mention/index',
    })
  },

  clickmoney: function (e) {
    console.log(e);
    wx.navigateTo({
      url: '/pages/voice_box/index/index',
    })
  },

  clickshares:function(){
    wx.navigateTo({
      url: '/pages/voice_box/forward/index?pages=1&code_url=' + this.data.code_url + '&id=' + this.data.redid,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({ redid: options.id });
    if (wx.getStorageSync('openid') == '') {
      app.app_load(that.log_load);
    } else {
      that.log_load();
    }
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success(res) {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              console.log(res);
            }
          })
        }
      }
    })
  },

  log_load: function (e,c) {
    wx.showLoading({ title: 'loading', mask: true });
    var openid = wx.getStorageSync('openid');
    if (openid == '' || openid == null) {
      openid = c;
    }
    var that = this;
    console.log('openid:', wx.getStorageSync('openid'));
    console.log('redid:', that.data.redid);
    //加载音频
    app.token_md5();
    wx.request({
      url: app.url2 + 'api/cdvoiceLoad', //录音接口
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        redid: that.data.redid,
        openid: openid,
        token: wx.getStorageSync('token_md5'),
      },
      method: 'GET',
      success: function (res) {
        var data = res.data;
        console.log(res);
        var timestamp = Date.parse(new Date())/1000;
        console.log(timestamp);
        console.log(data.created_at);
        if (data.created_at + 86400 < timestamp){
          that.setData({ open:1});
        }
        that.setData({
          current_user: data.current_user,//保存进入页面的当前用户的id
          voice_answer: data.data,
          voice_img: data.udata,
          state: data.state,
          voice_record: data.vdata.data,
          cashbox: data.cashbox,
          code_url: data.code_url,
        })
        wx.hideLoading();
      },
    });

    this.wallet(c);
  },

  wallet: function (e) {
    console.log(wx.getStorageSync('openid'));
    wx.showLoading({ title: 'loading', mask: true })
    var that = this;
    var openid = wx.getStorageSync('openid');
    if (openid == '' || openid == null) {
      openid = e;
    }
    app.token_md5();
    wx.request({
      url: app.url2 + 'api/yue',
      data: {
        openid: openid,
        token: wx.getStorageSync('token_md5'),
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {

      }
    })
  },

  //录音开始
  touchdown: function (e) {
    console.log("手指按下了...")
    console.log("new date : " + new Date)
    var _this = this;
    speaking.call(this);
    console.log(speaking.call);
    this.setData({
      speak: false,
      isspeaks:false
    })
    console.log('开始录音');
    //录音start
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    const options = {
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 72000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
    //end
  },

  //录音完成
  touchup: function (e) {
    console.log("手指抬起了...")
    var that = this;
    that.setData({
      speak: true,
      isspeaks:true,
      scrollHeight:99999999,
    })
    clearInterval(that.timer);
    //录音停止
    recorderManager.stop();
    //录音停止事件
    recorderManager.onStop((res) => {
      wx.showLoading({ title: 'loading', mask: true })
      console.log('recorder stop', res)
      const { tempFilePath } = res.tempFilePath;
      var redid = that.data.redid;
      var aaa = parseInt(res.duration / 1000);

      wx.uploadFile({
        url: app.url2 + 'api/cdvoiceUpload', //录音接口
        filePath: res.tempFilePath,
        header: { "Content-Type": "multipart/form-data" },
        name: "file",
        formData: {
          'redid': redid,
          'openid': wx.getStorageSync('openid'),
          'duration': aaa,
          'token': wx.getStorageSync('token_md5'),          
        },
        success: function (res0) {//录音返回结果
          var data = res0.data
          console.log(data);

          if (data == '1002') {//上传或转码失败
            wx.hideLoading();
            filing('系统繁忙，请稍后再试', 'loading');
          } else if (data == '1001') {//识别失败
            wx.hideLoading();
            filing('录音的姿势不对', 'loading');
          } else if (data == '1000') {//领取完
            that.setData({ state: 2 });
            wx.hideLoading();
            filing('被领完了', 'loading');
          } else if (data == '1003') {//猜错3次
            that.setData({ state: 4 });
            wx.hideLoading();
            filing('已猜错3次,不能再猜了', 'loading');
          } else if (data == 'not') {//不存在
            wx.hideLoading();
            filing('页面不存在', 'loading');
          } else {//匹配成功，领取
            var voice_record = that.data.voice_record;
            var kdata = JSON.parse(data);
            kdata.istrue = true;
            kdata.price = kdata.price.toFixed(2);
            kdata.created_at = (getLocalTime(kdata.created_at));
            var voice_answer = that.data.voice_answer;
            if (kdata.is_correct == 1) {
              voice_answer.s_number--;
            }
            console.log(voice_record);
            voice_record.push(kdata);
            that.setData({
              cashbox: kdata.price,
              state: kdata.state,
              voice_record: voice_record,
              voice_answer: voice_answer,
            });
            if (kdata.chao == '1003') {
              that.setData({ state: 4 });
            }
            console.log(voice_record);
          }


          wx.hideLoading();


        },
        fail: function (res1) {//上传失败
          console.log(res1);
        },
      })

    })

    //录音错误
    recorderManager.onError((res) => {
      console.log(res);
      filing('录音时间太短了', 'loading');
    })
  },

  //播放语音
  play_click: function (e) {
    var that = this;
    var user_id = e.currentTarget.dataset.user_id;
    var url = '';
    var voice_record = that.data.voice_record;

    if (user_id == 'master') {
      url = that.data.voice_answer.voice_url;
    } else {
      url = voice_record[user_id].voice_url;
    }


    if (that.data.listen != user_id) {
      that.innerAudioContext.src = url;
      that.innerAudioContext.onPlay(() => {
        console.log('开始播放');
        that.setData({ listen: user_id, })
      });
      that.innerAudioContext.play();

      //音频自然播放结束事件
      that.innerAudioContext.onEnded((res) => {
        that.setData({ listen: 'xxx', })
      })
    } else {
      //音频停止事件
      console.log('音频停止事件');
      that.innerAudioContext.stop()
      that.setData({
        listen: 'xxx',
        innerAudioContext: wx.createInnerAudioContext(),
      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.innerAudioContext = wx.createInnerAudioContext();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({ title: 'loading', mask: true });
    var that = this;
    console.log('下拉刷新开始···');
    // that.log_load();
    wx.hideLoading();
    app.token_md5();
    wx.request({
      url: app.url2 + 'api/cdvoiceLoad',
      header: {
        "Content-Type": "multipart/form-data"
      },
      data: {
        redid: that.data.redid,
        openid: wx.getStorageSync('openid'),
        token: wx.getStorageSync('token_md5'),
        page: ++that.data.page,
      },
      method: 'GET',
      success: function (res) {
        console.log(res);
        that.setData({
          page: that.data.page,
          //   current_user: data.current_user,//保存进入页面的当前用户的id
          //   voice_answer: data.data,
          //   voice_img: data.udata,
          //   state: data.state,
          //   voice_record: data.vdata.data,
          //   cashbox: data.cashbox
        })
        wx.stopPullDownRefresh()
        wx.hideLoading();
        console.log('下拉刷新结束···');
        if (res.data.vdata.data != '') {
          prompt('刷新成功', 'success')
        } else {
          prompt('没有更多了', 'loading')
        }
      },
      fail: function (res) {
        console.log(res.data)
        wx.hideLoading();
        //提示信息
        prompt('加载失败', 'loading')
      },
    });

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

//麦克风帧动画 
function speaking() {
  var _this = this;
  //话筒帧动画 
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

function filing(text, state) {
  wx.showToast({
    title: text,
    icon: state,
    duration: 1000,
    mask: true
  })
}

// 日期计算
function getLocalTime(nS) {
  var Y, M, D, W, H, I, S;
  function fillZero(v) {
    if (v < 10) { v = '0' + v; }
    return v;
  }
  var d = new Date(parseInt(nS) * 1000);
  M = fillZero(d.getMonth() + 1);
  D = fillZero(d.getDate());
  H = fillZero(d.getHours());
  I = fillZero(d.getMinutes());
  var localTime = M + '月' + D + '日 ' + H + ':' + I;
  return localTime;
}

// 提示信息
function prompt(text, status) {
  wx.showToast({
    title: text,
    icon: status,
    duration: 1200,
  })
}